package view;

import model.Video;
import javafx.embed.swing.JFXPanel;
import javafx.application.Platform;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.List;
import javafx.util.Duration;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class FrontView extends JFrame {
    private final JList<Video> videoList;
    private final DefaultListModel<Video> listModel;
    private final JButton playButton;
    private final JButton stopButton;
    private final JButton nextButton;
    private final JPanel videoPanel;
    private final JPanel controlPanel;
    private JButton pauseButton;
    private JSlider progressSlider;
    private JPanel mainVideoContainer;
    private MediaPlayer currentPlayer;
    private static final Logger LOGGER = Logger.getLogger(FrontView.class.getName());
    private boolean isPaused = false;
    private boolean userIsDraggingSlider = false;

    public FrontView() {
        // 设置窗口基础属性
        setTitle("在线视频播放器 - 美化版");
        setSize(1000, 700);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // 设置整体UI风格
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, "无法设置系统外观", e);
        }

        // ==================== 视频列表美化 ====================
        listModel = new DefaultListModel<>();
        videoList = new JList<>(listModel);
        videoList.setCellRenderer(new VideoListRenderer());
        videoList.setBackground(new java.awt.Color(45, 45, 45));
        videoList.setForeground(java.awt.Color.WHITE);
        videoList.setSelectionBackground(new java.awt.Color(70, 130, 180));
        videoList.setFixedCellHeight(50);
        videoList.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        JScrollPane listScrollPane = new JScrollPane(videoList);
        listScrollPane.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, new java.awt.Color(100, 100, 100)));
        add(listScrollPane, BorderLayout.WEST);

        // ==================== 主视频容器美化 ====================
        mainVideoContainer = new JPanel(new BorderLayout());
        mainVideoContainer.setBackground(java.awt.Color.BLACK);
        mainVideoContainer.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        // ==================== 视频播放面板 ====================
        videoPanel = new JPanel(new BorderLayout());
        videoPanel.setBackground(java.awt.Color.BLACK);
        mainVideoContainer.add(videoPanel, BorderLayout.CENTER);

        // ==================== 控制面板美化 ====================
        controlPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 10));
        controlPanel.setBackground(new java.awt.Color(30, 30, 30));
        controlPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));

        // 按钮美化
        playButton = createStyledButton("播放", new java.awt.Color(50, 150, 50));
        stopButton = createStyledButton("停止", new java.awt.Color(180, 50, 50));
        pauseButton = createStyledButton("暂停", new java.awt.Color(70, 130, 180));
        nextButton = createStyledButton("下一首", new java.awt.Color(70, 130, 180));

        controlPanel.add(playButton);
        controlPanel.add(pauseButton);
        controlPanel.add(stopButton);
        controlPanel.add(nextButton);

        // ==================== 进度条美化 ====================
        JPanel progressPanel = new JPanel(new BorderLayout());
        progressPanel.setBackground(new java.awt.Color(30, 30, 30));
        progressPanel.setBorder(BorderFactory.createEmptyBorder(0, 20, 10, 20));

        progressSlider = new JSlider(0, 100, 0);
        progressSlider.setBackground(new java.awt.Color(30, 30, 30));
        progressSlider.setForeground(java.awt.Color.WHITE);
        progressSlider.setUI(new CustomSliderUI(progressSlider)); // 自定义滑块样式

        progressSlider.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                userIsDraggingSlider = true;
            }
            @Override
            public void mouseReleased(MouseEvent e) {
                userIsDraggingSlider = false;
                if (currentPlayer != null) {
                    double fraction = progressSlider.getValue() / 100.0;
                    Duration seekTime = currentPlayer.getTotalDuration().multiply(fraction);
                    currentPlayer.seek(seekTime);
                }
            }
        });

        progressPanel.add(progressSlider, BorderLayout.CENTER);
        mainVideoContainer.add(progressPanel, BorderLayout.SOUTH);

        // ==================== 组装主界面 ====================
        add(mainVideoContainer, BorderLayout.CENTER);
        add(controlPanel, BorderLayout.SOUTH);

        // 初始化按钮状态
        updateButtonStates(false);
    }

    // 创建美化按钮的辅助方法
    private JButton createStyledButton(String text, java.awt.Color bgColor) {
        JButton button = new JButton(text);
        button.setBackground(bgColor);
        button.setForeground(java.awt.Color.WHITE);
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createEmptyBorder(8, 15, 8, 15));
        button.setFont(new Font("微软雅黑", Font.BOLD, 14));
        return button;
    }

    // ==================== 原有功能方法（保持不变） ====================
    public void setVideoList(List<Video> videos) {
        listModel.clear();
        for (Video video : videos) {
            listModel.addElement(video);
        }
        updateButtonStates(false);
    }

    public Video getSelectedVideo() {
        return videoList.getSelectedValue();
    }

    public MediaPlayer getCurrentPlayer() {
        return currentPlayer;
    }

    public void addPlayButtonListener(ActionListener listener) {
        playButton.addActionListener(listener);
    }

    public void addStopButtonListener(ActionListener listener) {
        stopButton.addActionListener(listener);
    }

    public void addNextButtonListener(ActionListener listener) {
        nextButton.addActionListener(listener);
    }

    public void addPauseButtonListener(ActionListener listener) {
        pauseButton.addActionListener(listener);
    }

    private void updateButtonStates(boolean isPlaying) {
        playButton.setEnabled(!isPlaying);
        stopButton.setEnabled(isPlaying);
        pauseButton.setEnabled(isPlaying);
        nextButton.setEnabled(listModel.size() > 1);
    }

    public void playNextVideo() {
        int currentIndex = videoList.getSelectedIndex();
        if (currentIndex < listModel.size() - 1) {
            videoList.setSelectedIndex(currentIndex + 1);
            Video nextVideo = getSelectedVideo();
            if (nextVideo != null) {
                playVideo(nextVideo.getFilePath());
            }
        } else {
            JOptionPane.showMessageDialog(this,
                    "已经是最后一个视频",
                    "提示",
                    JOptionPane.INFORMATION_MESSAGE);
        }
    }

    public void playVideo(String resourcePath) {
        if (currentPlayer != null) {
            currentPlayer.stop();
            currentPlayer.dispose();
            currentPlayer = null;
        }

        videoPanel.removeAll();

        try {
            final JFXPanel fxPanel = new JFXPanel();
            videoPanel.add(fxPanel, BorderLayout.CENTER);
            videoPanel.revalidate();
            videoPanel.repaint();

            URL videoUrl = getClass().getResource(resourcePath);
            if (videoUrl == null) {
                throw new FileNotFoundException("资源未找到: " + resourcePath);
            }

            Platform.runLater(() -> {
                try {
                    Media media = new Media(videoUrl.toExternalForm());
                    currentPlayer = new MediaPlayer(media);

                    currentPlayer.statusProperty().addListener((obs, oldStatus, newStatus) -> {
                        SwingUtilities.invokeLater(() -> updateButtonStates(newStatus == MediaPlayer.Status.PLAYING));
                    });

                    currentPlayer.currentTimeProperty().addListener((obs, oldTime, newTime) -> {
                        if (!userIsDraggingSlider && currentPlayer.getTotalDuration().greaterThan(Duration.ZERO)) {
                            double progress = newTime.toMillis() / currentPlayer.getTotalDuration().toMillis();
                            SwingUtilities.invokeLater(() -> {
                                progressSlider.setValue((int)(progress * 100));
                            });
                        }
                    });

                    currentPlayer.setOnEndOfMedia(() -> {
                        SwingUtilities.invokeLater(() -> {
                            if (videoList.getSelectedIndex() < listModel.size() - 1) {
                                nextButton.setEnabled(true);
                            }
                        });
                    });

                    currentPlayer.setOnError(() -> {
                        SwingUtilities.invokeLater(() -> {
                            JOptionPane.showMessageDialog(FrontView.this,
                                    "播放错误: " + currentPlayer.getError().getMessage(),
                                    "错误",
                                    JOptionPane.ERROR_MESSAGE);
                            updateButtonStates(false);
                        });
                    });

                    MediaView view = new MediaView(currentPlayer);
                    view.setPreserveRatio(true);
                    view.setFitWidth(videoPanel.getWidth());
                    view.setFitHeight(videoPanel.getHeight());

                    StackPane root = new StackPane(view);
                    root.setStyle("-fx-background-color: black;");
                    fxPanel.setScene(new Scene(root, Color.BLACK));

                    currentPlayer.play();
                    updateButtonStates(true);

                } catch (Exception e) {
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(FrontView.this,
                                "初始化失败: " + e.getMessage(),
                                "错误",
                                JOptionPane.ERROR_MESSAGE);
                        updateButtonStates(false);
                    });
                }
            });
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this,
                    "加载失败: " + e.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
            updateButtonStates(false);
        }
    }

    public void pauseVideo() {
        if (currentPlayer != null && currentPlayer.getStatus() == MediaPlayer.Status.PLAYING) {
            currentPlayer.pause();
            isPaused = true;
            pauseButton.setText("继续");
            pauseButton.setBackground(new java.awt.Color(70, 130, 180));
        }
    }

    public void resumeVideo() {
        if (currentPlayer != null && isPaused) {
            currentPlayer.play();
            isPaused = false;
            pauseButton.setText("暂停");
            pauseButton.setBackground(new java.awt.Color(70, 130, 180));
        }
    }

    public void togglePause() {
        if (isPaused) {
            resumeVideo();
        } else {
            pauseVideo();
        }
    }

    @Override
    public void dispose() {
        if (currentPlayer != null) {
            currentPlayer.stop();
            currentPlayer.dispose();
        }
        super.dispose();
    }

    // ==================== 自定义列表渲染器 ====================
    private static class VideoListRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                                                      boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if (value instanceof Video) {
                Video video = (Video) value;
                setText("<html><b>" + video.getTitle() + "</b> <font color='#AAAAAA'>(" + video.getViewCount() + "次播放)</font></html>");
                setIcon(new ImageIcon(video.getThumbnailPath())); // 假设Video类有缩略图路径
                setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
            }
            return this;
        }
    }

    // ==================== 自定义滑块UI ====================
    private static class CustomSliderUI extends javax.swing.plaf.basic.BasicSliderUI {
        private static final Color TRACK_COLOR = Color.rgb(80, 80, 80);
        private static final Color THUMB_COLOR = Color.rgb(70, 130, 180);

        public CustomSliderUI(JSlider slider) {
            super(slider);
        }

        @Override
        public void paintTrack(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            Rectangle trackBounds = trackRect;
            g2d.setColor(new java.awt.Color(80, 80, 80));
            g2d.fillRoundRect(trackBounds.x, trackBounds.y + trackBounds.height/2 - 2,
                    trackBounds.width, 4, 2, 2);

            if (slider.isEnabled()) {
                int fillWidth = thumbRect.x + thumbRect.width/2 - trackBounds.x;
                g2d.setColor(new java.awt.Color(70, 130, 180));
                g2d.fillRoundRect(trackBounds.x, trackBounds.y + trackBounds.height/2 - 2,
                        fillWidth, 4, 2, 2);
            }
        }

        @Override
        public void paintThumb(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            g2d.setColor(new java.awt.Color(70, 130, 180));
            g2d.fillOval(thumbRect.x, thumbRect.y + thumbRect.height/4,
                    thumbRect.width, thumbRect.height/2);
        }
    }
}